package action.newelifile;

import java.io.IOException;
import java.net.SocketException;
import java.util.Locale;

import org.apache.commons.net.ftp.FTPClient;

import action.pojo.FtpConnect;
import action.util.FtpConnectSQLITE;
import action.util.LoadSetting;
import action.util.Tool;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class EditServerFTP extends Activity{
	public FtpConnectSQLITE ftpConnectSQLITE;

	TextView lbserver,lbport,lbusername,lbpassword,tvHeader;
	EditText vlserver,vlport,vlusername,vlpassword;
	AsyncTask<String, String, Void> asyn;
	int DIALOG_DOWNLOAD_PROGRESS = 0;
	ProgressDialog mProgressDialog;

	Button login,cancel;
	boolean flag = false;
	FtpConnect ftp = new FtpConnect();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		LoadSetting.load(this);
		initLocale();
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.popup__new_server);
		getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));

		ftpConnectSQLITE = new FtpConnectSQLITE(this);
		ftpConnectSQLITE.open();

		initAttribute();
		
		ftp = (FtpConnect) getIntent().getExtras().get("ftp");
		initData();
		
		super.onCreate(savedInstanceState);
	}

	public void initLocale() {
		String languageToLoad = Tool.locale(LoadSetting.setting.getLanguage());
		Locale locale = new Locale(languageToLoad);
		Locale.setDefault(locale);
		Configuration config = new Configuration();
		config.locale = locale;
		getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
	}

	public void initAttribute(){
		lbserver = (TextView)findViewById(R.id.lbserver);
		lbport = (TextView)findViewById(R.id.lbport);
		lbusername = (TextView)findViewById(R.id.lbusername);
		lbpassword = (TextView)findViewById(R.id.lbpassword);

		vlserver = (EditText)findViewById(R.id.etServer);
		vlport = (EditText)findViewById(R.id.etPort);
		vlusername = (EditText)findViewById(R.id.etUsername);
		vlpassword = (EditText)findViewById(R.id.etPassword);

		login = (Button)findViewById(R.id.btLogin);
		cancel = (Button)findViewById(R.id.btCancel);

		lbserver.setText(getString(R.string.hostname));
		lbport.setText(getString(R.string.port));
		lbusername.setText(getString(R.string.username));
		lbpassword.setText(getString(R.string.password));
		login.setText(getString(R.string.ok));
		cancel.setText(getString(R.string.cancel));
		
		tvHeader = (TextView)findViewById(R.id.tvHeader);
		tvHeader.setText(getString(R.string.lbeditserver));

		login.setOnClickListener(proccessLoginButton());
		cancel.setOnClickListener(processCancelButton());
	}
	
	public void initData(){
		vlserver.setText(ftp.getHostname());
		vlport.setText(ftp.getPort());
		vlusername.setText(ftp.getUsername());
		vlpassword.setText(ftp.getPassword());
	}

	// process ok button
	OnClickListener proccessLoginButton(){
		OnClickListener onclick = new OnClickListener() {

			@Override
			public void onClick(View v) {
				if(vlserver.getText()==null || vlserver.getText().equals("")){
					Toast.makeText(EditServerFTP.this, "Enter server address", Toast.LENGTH_SHORT).show();
				}else{
					check();
				}
			}
		};
		return onclick;
	}

	// check

	public void check(){

		asyn = new AsyncTask<String, String, Void>() {

			protected void onPreExecute() {
				showDialog(DIALOG_DOWNLOAD_PROGRESS);
			}

			protected void onProgressUpdate(String... progress) {
				mProgressDialog.setMessage(progress[0]);
			}

			protected Void doInBackground(String... params) {
				try {
					mProgressDialog.setMessage("Checking ...");
					if(!vlserver.getText().toString().equals("") && !vlport.getText().toString().equals("")
							&& !vlusername.getText().toString().equals("") && !vlpassword.getText().toString().equals("")){

						FTPClient client = new FTPClient();

						client.connect(vlserver.getText().toString(),Integer.parseInt(vlport.getText().toString()));
						flag = client.login(vlusername.getText().toString(), vlpassword.getText().toString());

						if(flag){
							ftp.setHostname(vlserver.getText().toString());
							ftp.setPort(Integer.parseInt(vlport.getText().toString()));
							ftp.setUsername(vlusername.getText().toString());
							ftp.setPassword(vlpassword.getText().toString());
							
							ftpConnectSQLITE.updateFtp(ftp);
							
							Intent intent = new Intent(EditServerFTP.this,FtpActivity.class);
							startActivity(intent);
						}else{
							Toast.makeText(EditServerFTP.this, "Connection failed", Toast.LENGTH_SHORT).show();
						}
					}
				} catch (NumberFormatException e) {
					e.printStackTrace();
				} catch (SocketException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				return null;
			}


			protected void onPostExecute(Void arg) {
				if (mProgressDialog.isShowing()) {
					mProgressDialog.dismiss();
					if(flag){ 
						finish();
					}
				}
			}
		};
		asyn.execute("");

	}
	
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case LocalActivity.DIALOG_DOWNLOAD_PROGRESS:
			mProgressDialog = new ProgressDialog(this);
			mProgressDialog.setTitle("Checking ...");
			mProgressDialog.setCancelable(false);
			mProgressDialog.show();
			return mProgressDialog;
		default:
			return null;
		}
	}
	// process cancel button
	OnClickListener processCancelButton(){
		OnClickListener onClick = new OnClickListener() {

			@Override
			public void onClick(View v) {
				setResult(0);
				finish();
			}
		};
		return onClick;
	}
}
